package com.hornsun.repository;

import com.google.common.base.Preconditions;
import com.hornsun.domain.dbo.Address;
import com.hornsun.domain.dbo.AddressExample;
import com.hornsun.repository.mapper.AddressMapper;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by 编译中... on 2018/4/27.
 */
@Repository
public class AddressRepository {

    @Resource
    private AddressMapper addressMapper;

    /**
     * 通过openid获取用户地址
     * @param openid
     * @return
     */
    public List<Address> getAddressesByOpenid(String openid){
        Preconditions.checkNotNull(openid);
        AddressExample addressExample  = new AddressExample();
        AddressExample.Criteria criteria = addressExample.createCriteria();
        criteria.andOpenidEqualTo(openid);
        return addressMapper.selectByExample(addressExample);
    }

    /**
     * 获取默认地址
     * @param openid
     * @return
     */
    public List<Address> getDefaultAddress(String openid){
        Preconditions.checkNotNull(openid);
        AddressExample addressExample  = new AddressExample();
        AddressExample.Criteria criteria = addressExample.createCriteria();
        criteria.andOpenidEqualTo(openid).andIsDefaultEqualTo(true);
        return addressMapper.selectByExample(addressExample);
    }

    public Address getAddressByGuid(String addressGuid){
        Preconditions.checkNotNull(addressGuid);
        return addressMapper.selectByPrimaryKey(addressGuid);
    }

    /**
     * 删除地址
     * @param addressGuid
     */
    public void deleteAddressByGuid(String addressGuid){
        Preconditions.checkNotNull(addressGuid);
        int count = addressMapper.deleteByPrimaryKey(addressGuid);
        if (count!=1){
            throw new IllegalArgumentException("delete address failed by addressGuid:"+addressGuid);
        }
    }

    /**
     * 修改地址
     * @param address
     */
    public void updateAddress(Address address){
        Preconditions.checkNotNull(address);
        int count = addressMapper.updateByPrimaryKeySelective(address);
        if (count!=1){
            throw new IllegalArgumentException("update address failed by address:"+address);
        }

    }

    /**
     * 新增地址
     * @param address
     */
    public void addAddress(Address address){
        Preconditions.checkNotNull(address);
        int count = addressMapper.insertSelective(address);
        if (count!=1){
            throw new IllegalArgumentException("add address dailed by address:"+address);
        }
    }

    public void resetIsDefault(String openid){
        addressMapper.resetIsDefault(openid);
    }

}
